﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SwaggerJwtAuthenticationCenter.Helper
{
    public class MultiDBConfig
    {
        public string ConnId { get; set; }
        public string Conn { get; set; }
        public DataBaseType DbType { get; set; }

        internal ConnectionConfig ConvertToConnConfig()
        {
            var connConfig = new ConnectionConfig()
            {
                ConfigId = ConnId.ObjToString().ToLower(),
                ConnectionString = Conn,
                DbType = (DbType)DbType,
                IsAutoCloseConnection = true,
                IsShardSameThread = false,
                AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, p) =>
                    {
                        // 多库操作的话，此处暂时无效果，在另一个地方有效，具体请查看BaseRepository.cs
                    }
                },
                MoreSettings = new ConnMoreSettings()
                {
                    IsAutoRemoveDataCache = true
                }
            };
            return connConfig;
        }
    }

    public enum DataBaseType
    {
        MySql = 0,
        SqlServer = 1,
        Sqlite = 2,
        Oracle = 3,
        PostgreSQL = 4
    }


    public class DBHelper
    {
        public static List<MultiDBConfig> GetCurrentDBConfigs(bool isMultiConfig = false)
        {
            List<MultiDBConfig> dBConfigs = Appsettings.app<MultiDBConfig>(new string[] { "DBS" });
            var mainDB = Appsettings.app("MainDB");
            if (isMultiConfig)
            {
                return dBConfigs;
            }
            else
            {
                return new List<MultiDBConfig>() { dBConfigs.Find(e=>e.ConnId.ToLower()== mainDB.ToLower()) };
            }

        }
    }
}
